const WebSocket = require('ws'); 
var express = require('express');
var router = express.Router();
router.get('/', function(req, res, next) {
    console.log(req);
    console.log(123)
const ws = new WebSocket.Server({port: 3003}, () => {
    console.log('socket start');
}) 
let clients = [];
ws.on('connection', (client) => {
    console.log(999)
    // 每个客户端连接时创建一个client，广播时要发给每一个，所以要把创建的client都丢到一个数组里面。
    clients.push(client);
    client.send('欢迎光临'); // 数据传输字符串
    client.on('message', (msg) =>{
        console.log('来自前端的数据：'+ msg);
        if(msg.includes('广播')){
            sendAll();
        }
    })
    client.on('close', (msg) =>{
        console.log('前端主动断开连接');
    })
})


// 广播发送给每个客户端
function sendAll() {
    for (let index = 0; index < clients.length; index++) {
        clients[index].send('开始📢：略略略略略~~~');
    }
}
});
// var express = require('express');
// var router = express.Router();

// /* GET users listing. */
// router.get('/', function(req, res, next) {
//   // res.send('respond with a resource');
//   res.json({
//     data: null,
//     message: "验证码已发送，验证码：ef5asd",
//     resCode: 0
//   })
// });

 module.exports = router;
